package game.core.phases 
{
	import flash.events.Event;
	import flash.geom.Point;
	import game.core.Player;
	import game.gui.Camera;
	import game.objects.Building;
	import net.flashpunk.utils.Input;
	import net.flashpunk.utils.Key;
	/**
	 * ...
	 * @author Sulus Ltd.
	 */
	public class SelectBuildingPhase extends TurnPhase
	{
		private var playerBuildings:Array;
		private var currentBuildingIdx:int;
		private var active:Boolean = true;
		private var buildingSelected:Boolean = false;
		private var lastFocus:Boolean;
		private var player:Player;
		
		public function SelectBuildingPhase() 
		{
			name = "режим выбора башни";
		}
		
		
		override public function Start():void 
		{
			trace("SelectBuildingPhase phase begins");
			
			
			player = papa.currentPlayer;
			if (!player) 
			{
				EndPhase();
				return;
			}
			
			var buildings:Array = papa.buildings;
			playerBuildings = [];
			for each (var building:Building in buildings)
			{
				if (building.player == player && building.controllable)
				playerBuildings.push(building);
			}
			
			if (playerBuildings.length == 0) 
			{
				EndPhase();
				return;
			}
			
			currentBuildingIdx = 0;
			
			SelectBuilding(currentBuildingIdx);
			
		}
		
		private function SelectBuilding(idx:int, finish:Boolean = false ):void 
		{
			if (idx < 0) idx = playerBuildings.length - 1;
			if (idx >= playerBuildings.length) idx = 0;
			
			currentBuildingIdx = idx;
			
			var building:Building = playerBuildings[idx];
			papa.world.gui.camera.MoveTo(new Point(building.x, building.y));
			active = false;
			lastFocus = finish;
			papa.world.gui.camera.eventDispatcher.addEventListener(Camera.EVENT_MOVE_COMPLETE, OnCameraFocused);
		}
		
		private function OnCameraFocused(e:Event):void 
		{
			if (lastFocus)
			{
				player.currentBuilding = playerBuildings[currentBuildingIdx];
				EndPhase();
			} else
			active = true;
		}
		
		override public function Update():void 
		{
			if (active)
			{
				if (Input.check(Key.LEFT)) 
				{
					SelectBuilding(currentBuildingIdx + 1);
				} else
				if (Input.check(Key.RIGHT))
				{
					SelectBuilding(currentBuildingIdx - 1);
				} else
				if (Input.pressed(Key.SPACE) || Input.pressed(Key.ENTER))
				{
					buildingSelected = true;
					active = false;
				}
			} else
			if (buildingSelected)
			{
				SelectBuilding(currentBuildingIdx, true);
			}
		}
		
		override public function Finish():void 
		{
			trace("SelectBuildingPhase phase ends");
			
			papa.world.gui.camera.eventDispatcher.removeEventListener(Camera.EVENT_MOVE_COMPLETE, OnCameraFocused);
		}
	}

}